﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Prism.Example.Events;
using Microsoft.Practices.Unity;


namespace Prism.Example.ModuleB
{
    
       [Module(ModuleName = "ModuleBInit")]
    public class ModuleBInit : IModule
    {

        private readonly IUnityContainer _container;
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;

        public ModuleBInit(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator)
        {                    
            this._container = container;
            this._regionManager = regionManager;
            _eventAggregator = eventAggregator;
        }

        public void Initialize()
        {
            this._container.RegisterType<object, Page1>( "Page1", new ContainerControlledLifetimeManager());
            _regionManager.AddToRegion("Main", this._container.Resolve(typeof(object), "Page1"));

            this._container.RegisterType<ModuleBController>(new ContainerControlledLifetimeManager());
            this._container.Resolve<ModuleBController>().Run();
        }

     
    }

       public class ModuleBController
       {
           private readonly IRegionManager _regionManager;
           private readonly IEventAggregator _eventAggregator;
           public ModuleBController(IRegionManager regionManager, IEventAggregator eventAggregator)
           {
               _regionManager = regionManager;
               _eventAggregator = eventAggregator;

           }
           public void Run()
           {
               _eventAggregator.GetEvent<OnChangeViewEvent>().Subscribe(x => OnChangeViewRequest(x));

           }
           private void OnChangeViewRequest(string viewName)
           {
               if (viewName.Equals("Page1"))
               {
                   NavigateToPage1();

               }
           }

           private void NavigateToPage1()
           {
               _regionManager.RequestNavigate("Main", "Page1");
           }
       }
}
